chrome.runtime.onConnect.addListener(function (port) {
    if (port.name === "aiAnswer") {
        port.onMessage.addListener(function (msg) {
            if (msg.action === "getAIAnswer") {
                fetchAIAnswer(msg.text, port);
            }
        });
    }
});

let conversationHistory = [
    { "role": "system", "content": "你是一个得力助手" }
];

async function fetchAIAnswer(text, port) {
    const apiKey = 'YOUR_API_KEY_HERE'; // 请替换为您的API密钥
    const url = 'https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation'; 
    conversationHistory.push({ "role": "user", "content": text });

    try {
        const response = await fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': `Bearer${apiKey} `,
                'X-DashScope-SSE': 'enable'
            },
            body: JSON.stringify({
                'model': 'qwen-turbo',
                "input": {
                    "messages": conversationHistory
                },
                "parameters": {
                    "incremental_output": true,
                    "result_format": "message"
                }
            })
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const reader = response.body.getReader();
        const decoder = new TextDecoder('utf-8');
        let fullResponse = '';

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value, { stream: true });
            port.postMessage({ type: 'chunk', data: chunk });

            // Extract content and append to fullResponse
            const match = /"content":"(.*?)(?<!\\)"/.exec(chunk);
            if (match) {
                const content = JSON.parse(`"${match[1]}"`);
                fullResponse += content;
            }
        }

        port.postMessage({ type: 'end' });

        // Update the conversation history with the assistant's response
        conversationHistory.push({ "role": "assistant", "content": fullResponse });

    } catch (error) {
        console.error('Error fetching AI answer:', error);
        port.postMessage({ type: 'error', error: error.message });
    }
}
